package com.axjy.item.service.impl;

import com.axjy.item.service.IndexFloorService;
import com.axjy.item.vo.*;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service("indexFloorService")
public class IndexFloorServiceImpl implements IndexFloorService {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public List<IndexFloorItems> queryFloorItems() {
        RMap<FloorKeyVo, List<ItemVo>> map= redissonClient.getMap("tp:item:floor");
        List<IndexFloorItems> list= map.keySet().stream().map(floorKeyVo->{
            IndexFloorItems indexFloorItems=new IndexFloorItems();
            BeanUtils.copyProperties(floorKeyVo,indexFloorItems);
            List<ItemVo> itemVos= map.get(floorKeyVo);
            List<FloorItemVo> floorItemVoList= itemVos.stream().map(itemVo -> {
                FloorItemVo vo=new FloorItemVo();
                BeanUtils.copyProperties(itemVo,vo);
                return vo;
            }).collect(Collectors.toList());
            indexFloorItems.setItems(floorItemVoList);
            return indexFloorItems;
        }).sorted((a,b)->a.getFloor()-b.getFloor()).collect(Collectors.toList());
        return list;
    }

    @Override
    public ItemDetailVo queryItemDetail(Integer id) {
        RMap<FloorKeyVo, List<ItemVo>> map= redissonClient.getMap("tp:item:floor");
        ItemVo result=null;
        for(List<ItemVo> list:map.values()){
            Optional<ItemVo> optional= list.stream().filter(itemVo -> id.equals(itemVo.getId()))
                     .findFirst();
            if(optional.isPresent()){
                result= optional.get();
                break;
            }
         }
        ItemDetailVo itemDetailVo=new ItemDetailVo();
         BeanUtils.copyProperties(result,itemDetailVo);
        return itemDetailVo;
    }
}
